package org.stvd.controller.web;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.stvd.entities.common.WebReflect;
import org.stvd.entities.common.WebReflectPK;
import org.stvd.service.common.WebReflectService;

/**
 * WEB转发-控制类
 * @author hzx
 */
@Controller
@RequestMapping("/web")
public class WebDispatcher {
    @Autowired
    private WebReflectService webReflectService;

    @RequestMapping(value = "portal")
    public String onPortal(HttpServletRequest request, ModelMap map) {
        String viewURL = request.getParameter("viewURL");
        if(viewURL != null && !viewURL.equals("")){
            String requestMethod = request.getMethod(); //请求类型：GET or POST
            //请求与处理类映射关系
            WebReflectPK mwebReflectPK = new WebReflectPK(viewURL, requestMethod.toUpperCase());
            WebReflect wr = webReflectService.findByPK(mwebReflectPK);
            if (wr != null) {
                //前台请求的处理结果
                Map<String, Object> resultMap = getData(request, wr.getCtrlName());
                map.addAllAttributes(resultMap);
                if (map!=null && map.containsKey("redirectUrl")) {
                    //处理结果包含重定向消息时，需重新定向到新页面
                    String redirectUrl = map.get("redirectUrl").toString();
                    map.remove("redirectUrl");
                    return "redirect:"+redirectUrl;
                } else if (map!=null && map.containsKey("viewURL")) {
                    //指定了显示路径
                    String viewUrl = map.get("viewURL").toString();
                    map.remove("viewURL");
                    return viewUrl;
                } else if (map!=null && map.containsKey("errorMsg")) {
                    String backUrl = request.getHeader("referer");
                    if (backUrl!=null && !"".equals(backUrl)) {
                        backUrl = backUrl.replace("https://", "http://");
                        backUrl = backUrl.replace("http://", "");
                        // 若有上一请求路径，在返回到上一请求路径
                        //网站根路径
                        StringBuffer serverHttp = new StringBuffer();
                        serverHttp.append(request.getScheme()+"://"+request.getServerName());
                        if (request.getServerPort() != 80) {
                            serverHttp.append(":"+request.getServerPort());
                        };
                        serverHttp.append(request.getContextPath());
                        //上个请求的前缀
                        String urlHeader = viewURL.substring(0, viewURL.indexOf("/", 1));
                        //返回当前页面
                        return urlHeader+backUrl.substring(backUrl.indexOf("/",1));
                    }
                }
                if (wr.getResponseUrl()!=null
                            && !"".equals(wr.getResponseUrl())) {
                    //处理类映射的响应地址不为空
                    viewURL = wr.getResponseUrl();
                }
            }
            return viewURL;
        }
        return null;
    }
    
    @SuppressWarnings("unchecked")
    private Map<String, Object> getData(HttpServletRequest request, String serviceName) {
        Map<String,Object> data = new HashMap<String,Object>();

        ServletContext servletContext = request.getSession().getServletContext(); 
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext );

        Method mh = ReflectionUtils.findMethod(ctx.getBean(serviceName).getClass(),
                "getData",new Class[]{HttpServletRequest.class} );
        data = (Map<String, Object>) ReflectionUtils.invokeMethod(mh, ctx.getBean(serviceName), new Object[]{request});
        return data ;
    }
}
